<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Model\Goods;

use DB;

class GoodsController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function index(Request $request)
	{
	   
		// 获取商品数据	
		if($request->has('name')){
			$name = $request->input('name');
			$datas = DB::table('goods')
			->join('shop', 'goods.shop_id', '=', 'shop.shop_id')
			->where('goods_name','like',"%{$name}%")
			->orderby('goods_id','desc')
			// ->join('goods_imgs', 'goods.id', '=', 'goods_imgs.goods_id')
			->paginate(5);
		}else{
			$datas = DB::table('goods')
			->join('shop', 'goods.shop_id', '=', 'shop.shop_id')
			->orderby('goods_id','desc')
			// ->join('goods_imgs', 'goods.id', '=', 'goods_imgs.goods_id')
			->paginate(5);
			$name = '';
		}
		
			
		// 获取遍历出的数据数目
		$num = count(Goods::All()); 
		return view('admin.goods_list')->with('goods',$datas)->with('num',$num)->with('name',$name);
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function create()
	{
		// 获取栏目数据
		$type = DB::table('cats')->get();

		// 获取店铺数据
		$shop = DB::table('shop')->get();

		//商品添加页面展示
		return view('admin.goods_add')->with('type',$type)->with('shop',$shop);
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @return \Illuminate\Http\Response
	 */

	// 商品添加
	public function store(Request $request)
	{
		// // 商品上传验证
		$this->validate($request, [
            'goods_name' => 'required|max:255',
            'shop_price' => 'required',
            'goods_price' => 'required',
            'shop_id' => 'required|integer',
            'cat_id'=>'required|integer',
            'number'=>'required|integer',
            'goods_detail'=>'required',
            'pic_detail' =>'required',
            'pic' =>'required',
            'color'=>'required',
            'size'=>'required',

        ],$this->messages());


		// 缩略图上传
		// 判断上传的文件是否有效
		if($request->file('pic')->isValid()){
			// 获取上传的文件对象
			$data = $request->file('pic');
			// 获取上传的文件的后缀
			$ext = $data->getClientOriginalExtension();
			// 拼装出你需要使用的文件名
			$picname = time().rand(1000,9999).'.'.$ext;
			// 移动临时文件，生成新文件到指定目录下
			$data->move(public_path('upload/images/'),$picname);
		}

		// 商品图片详情多图上传
		$imgs = $request->file('pic_detail');
        $urls=[];
        foreach($imgs as $img){
            if($img->isValid()){
                $ext = $img->getClientOriginalExtension(); //获取上传文件名的后缀名
                $name = "detail_".time().rand(10,100).'.'.$ext;
                if($img->move(public_path('upload/images/'),$name)){
                    $url = $name;
                    $urls[]=['url'=>$url];
                }
            }
        }
		// 获取表单传过来的所有数据
		$data = $request->except('_token');
		// 重写pic值
		$data['pic'] = $picname;
		$data['url'] = $urls;
		// dd($data);

		// 插入商品主表
		$goods = Goods::create([
			'goods_name'=>$data['goods_name'],
			'goods_price'=>$data['goods_price'],
			'shop_price'=>$data['shop_price'],
			'shop_id'=>$data['shop_id'],
			'number'=>$data['number'],
			'cat_id'=>$data['cat_id'],
			'goods_detail'=>$data['goods_detail'],
			'pic'=>$data['pic'],
			]);
		// 插入商品附表
		$goods_info=[];
		$goods_info['size'] = $data['size'];
		$goods_info['color'] = $data['color'];
		$goods_info['goods_id'] = $goods->id;
		DB::table('goods_info')->insert($goods_info);

		// 插图商品图片附表
		$goods_imgs = [];
 
		foreach ($urls as $k=>$url ) {
			$goods_imgs[$k]['goods_id'] = $goods->id;
		    $goods_imgs[$k]['cat_id'] = $data['cat_id'];
		    $goods_imgs[$k]['url'] = $url['url'];
		}
		
		DB::table('goods_imgs')->insert($goods_imgs);
		return redirect('admin/goods')->with('msg','添加成功');
	}

	public function messages()
    {
        return [
            'goods_name.required' => '请填写商品名称',
            'shop_price.required'  => '请填写商品店铺价格',            'shop_price.integer'  => '',
            'goods_price.required'  => '请填写商品销售价格',
            'number.required' => '请填写商品库存',
            'number.integer' => '商品库存为整数',
            'pic.required' => '请上传商品缩略图',
            'color.required' => '请填写商品颜色属性',
            'size.required' => '请填写商品尺寸属性',
            'pic_detail.required' => '请上传商品详情图',
            'goods_detail.required' => '请填写商品详情',
            'cat_id.required' => '请选择商品栏目',
            'shop_id.required' => '请选择店铺',
        ];
    }

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return \Illuminate\Http\Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return \Illuminate\Http\Response
	 */
	public function edit($id)
	{
		//获取商品数据
		$data = DB::table('goods')
		->join('goods_info','goods_info.goods_id','=','goods.goods_id')
		->where('goods.goods_id','=',$id)
		->get();
		// dd($data);
		// 获取栏目数据
		$type = DB::table('cats')->get();

		// 获取店铺数据
		$shop = DB::table('shop')->get();

		// 获取商品附加表

		return view('admin.goods_edit')->with('data',$data)->with('type',$type)->with('shop',$shop);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  int  $id
	 * @return \Illuminate\Http\Response
	 */
	public function update(Request $request, $id)
	{
		// 图片上传
		if($request->hasFile('pic')){
			// 判断上传的文件是否有效
			if($request->file('pic')->isValid()){
				// 获取上传的文件对象
				$data = $request->file('pic');
				// dd($data);
				// 获取上传的文件的后缀
				$ext = $data->getClientOriginalExtension();
				// 拼装出你需要使用的文件名
				$picname = time().rand(1000,9999).'.'.$ext;
				// $path = public_path('upload/images/')
				// 移动临时文件，生成新文件到指定目录下
				$data->move(public_path('upload/images/'),$picname);
			}
				// 修改主表
				$goods = Goods::where('goods_id',$id)->update([
				'goods_name'=>$request->goods_name,
				'goods_price'=>$request->goods_price,
				'shop_price'=>$request->shop_price,
				'shop_id'=>$request->shop_id,
				'number'=>$request->number,
				'cat_id'=>$request->cat_id,
				'goods_detail'=>$request->goods_detail,
				'pic'=>$picname,
				]);

				// 更新附表
				$goods_info = DB::table('goods_info')
				->where('goods_id',$id)
				->update([
					'size'=>$request->size,
					'color'=>$request->color,
					'goods_id'=>$id,
					]);
				return redirect('admin/goods');
			
		}else{
			// 修改主表
				$goods = Goods::where('goods_id',$id)->update([
				'goods_name'=>$request->goods_name,
				'goods_price'=>$request->goods_price,
				'shop_price'=>$request->shop_price,
				'shop_id'=>$request->shop_id,
				'number'=>$request->number,
				'cat_id'=>$request->cat_id,
				'goods_detail'=>$request->goods_detail,
				'pic'=>$request->oldpicname,
				]);

				// 更新附表
				$goods_info = DB::table('goods_info')
				->where('goods_id',$id)
				->update([
					'size'=>$request->size,
					'color'=>$request->color,
					'goods_id'=>$id,
					]);
				return redirect('admin/goods');
		}

		// dd($request->input('controller'));
		// $row = DB::table('goods')->where('goods_id',$id)->update($data);

		// if($row>0){
		// 	return redirect('admin/goods')->with('msg','修改成功');
		// }else{
		// 	return redirect('admin/goods')->with('error','修改失败');
		// }

		
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return \Illuminate\Http\Response
	 */
	public function destroy($id)
	{
		//
	}

	// 商品删除
	public function delete($id)
	{
		$data = DB::table('goods')->where('goods_id',$id)->delete();
		if ($data) {
		   return redirect('admin/goods');
		}
		
	}

	// 商品状态修改
	public function status($id)
	{
		$data = DB::table('goods')->where('goods_id',$id)->first();
		if($data->status){
			$status = 0;
			DB::table('goods')->where('goods_id',$id)->update(['status'=>$status]);
			return redirect('admin/goods');
		}else{ 
			$status = 1;
			DB::table('goods')->where('goods_id',$id)->update(['status'=>$status]);
			return redirect('admin/goods');
		}
	}
}
